import React, { Component } from 'react';

//导入echarts
var echarts = require('echarts/lib/echarts') //必须
require('echarts/lib/chart/pie') //图表类型
require('echarts/lib/component/title') //标题插件

import {setFontSize} from '../../util'

class PieReact extends React.Component {

  constructor(props) {
    super(props)
    this.setPieOption = this.setPieOption.bind(this)
    this.initPie = this.initPie.bind(this)
  }

  initPie() {
    const { data } = this.props; //外部传入的data数据
    let myChart = echarts.init(this.refs.pieChart); //初始化echarts

    //我们要定义一个setPieOption函数将data传入option里面
    let options = this.setPieOption(data);
    //设置options
    myChart.setOption(options)
  }

  componentDidMount() {
    this.initPie()
  }

  componentDidUpdate() {
    this.initPie()
  }


  render() {
    return (
      <div className="echart-react">
        <div ref="pieChart" style={{width: "100%", height: setFontSize(3.5)}}></div>
      </div>
    )
  }

   getData(percent) {
      return [{
        value: percent,
        itemStyle: {
          normal: {
            color: '#41C0E4',
            shadowBlur: 10,
            shadowColor: '#41C0E4'
          }
        }
      }, {
        value: 1 - percent,
        itemStyle: {
          normal: {
            color: '#c7c7c9'
          }
        }
      }];
    }
  //一个基本的echarts图表配置函数
  setPieOption(data) {
    let ratio = (data.ratio * 100).toString();
    let titleData =ratio.split('.');
    return {
      title: {
        text: titleData[0] + '%',
        subtext: '录取概率',
        x: 'center',
        y: '43%',
        textStyle: {
          color: '#41C0E4',
          fontSize: setFontSize(0.72)
        },
        subtextStyle: {
          color: '#9B9B9B',
          fontSize: setFontSize(0.24)
        }
      },
      animation: false,
      series: [{
        type: 'pie',
        radius: ['48%', '53%'],
        silent: true,
        label: {
          normal: {
            show: false
          }
        },
        data: [{
          itemStyle: {
            normal: {
              color: '#3da1ee',
              shadowBlur: 2,
              shadowColor: '#3da1ee'
            }
          }
        }]
      }, {
        name: 'main',
        type: 'pie',
        radius: ['66%', '76%'],
        label: {
          normal: {
            show: false
          }
        },
        data: this.getData(data.ratio)
      }]
    };

  }
}
export default PieReact
